package com.lg.atp.service.impl;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.lg.atp.common.Constants;
import com.lg.atp.dao.AttachmentDao;
import com.lg.atp.dao.CaseInfoDao;
import com.lg.atp.dao.CaseStepDao;
import com.lg.atp.dao.ControlDao;
import com.lg.atp.dao.DeviceInfoDao;
import com.lg.atp.dao.ParaDao;
import com.lg.atp.dao.ParaDataDao;
import com.lg.atp.dao.TblTestTaskCaseDeviceMapper;
import com.lg.atp.dao.TblTestTaskCaseMapper;
import com.lg.atp.dao.TblTestTaskCaseRunMapper;
import com.lg.atp.dao.TblTestTaskMapper;
import com.lg.atp.entity.TblAppInfo;
import com.lg.atp.entity.TblAttachment;
import com.lg.atp.entity.TblCaseInfo;
import com.lg.atp.entity.TblCaseStep;
import com.lg.atp.entity.TblControls;
import com.lg.atp.entity.TblDeviceInfo;
import com.lg.atp.entity.TblPara;
import com.lg.atp.entity.TblParaData;
import com.lg.atp.entity.TblTestTask;
import com.lg.atp.entity.TblTestTaskCase;
import com.lg.atp.entity.TblTestTaskCaseDevice;
import com.lg.atp.entity.TblTestTaskCaseRunWithBLOBs;
import com.lg.atp.sercurity.SecurityUserHolder;
import com.lg.atp.service.IAppInfoService;
import com.lg.atp.service.IDeviceInfoService;
import com.lg.atp.service.ScriptService;
import com.lg.atp.utils.DeviceConstants;
import com.lg.atp.utils.DeviceUtil;
import com.lg.atp.utils.JobParameter;
import com.lg.atp.utils.PictureTool;
import com.lg.atp.ws.WSClient;
@Service("scriptService")
public class ScriptServiceImpl implements ScriptService {

	private @Value("${targetFilePath}") String targetFilePath;
	private @Value("${serverIP}") String serverIP;
	private @Value("${openCvServer}") String openCvServer;
	private @Value("${serverPort}") Integer serverPort;
	private @Value("${relibleMasterIp}") String relibleMasterIp;
	private Log log = LogFactory.getLog(ScriptServiceImpl.class);
	@Autowired
	private TblTestTaskCaseMapper tblTestTaskCaseMapper;
	
	@Autowired
	private TblTestTaskMapper tblTestTaskMapper;
	@Autowired
	private AttachmentDao attachmentDao;
	@Autowired
	private TblTestTaskCaseDeviceMapper tblTestTaskCaseDeviceMapper;
	@Autowired
	private TblTestTaskCaseRunMapper tblTestTaskCaseRunMapper;
	
	@Autowired
	private CaseInfoDao caseInfoDao;
	@Autowired
	private CaseStepDao caseStepDao;
	
	@Autowired
	private IAppInfoService iAppInfoService;
	@Autowired
	private IDeviceInfoService deviceService;
	@Autowired
	private ControlDao controlDao;
	@Autowired
	private ParaDao paraDao;
	@Autowired
	private ParaDataDao paraDataDao;
	@Autowired
	private DeviceInfoDao deviceInfoDao;
	
	@Override
	public void generateScriptByTaskId(Long taskId) {
		TblTestTask tblTestTask = tblTestTaskMapper.selectByTaskId(taskId);
		List<TblTestTaskCase> caseList = tblTestTaskCaseMapper.selectByTaskId(taskId);
		List<TblTestTaskCaseDevice> deviceList = tblTestTaskCaseDeviceMapper.getTaskDeviceByTaskId(taskId);
		int count =0;
		//if (tblTestTask.getTestType()==1) {
			for (TblTestTaskCase tblTestTaskCase : caseList) {
				List<TblCaseStep> caseSteps = caseStepDao.selectStepByCaseId(tblTestTaskCase.getCaseId());
				for (int i=0;i<deviceList.size();i++) {
					
					if (tblTestTask.getTestType()==2&&i>0)break;
					TblTestTaskCaseDevice tblTestTaskCaseDevice=null;
					if (tblTestTask.getTestType()==1) {
						tblTestTaskCaseDevice =deviceList.get(i);
					}else {
						tblTestTaskCaseDevice =deviceList.get(count%deviceList.size());
					}
					count++;
					StringBuffer scriptHead = new StringBuffer();
					StringBuffer scriptBody = new StringBuffer();
					String scriptData ="";
					TblDeviceInfo deviceInfo = deviceInfoDao.selectByPrimaryKey(tblTestTaskCaseDevice.getDeviceId().intValue());
					for (TblCaseStep tblCaseStep : caseSteps) {
						TblPara readTblPara = null;
						TblPara writeTblPara = null;
						if (tblCaseStep.getOperateReadParaId()!=null) {
							readTblPara = paraDao.selectParaByParaId(tblCaseStep.getOperateReadParaId());
							scriptHead.append("var "+readTblPara.getParaName()+"=null;\r\n");
						}
						if (tblCaseStep.getOperateWriteParaId()!=null) {
							writeTblPara = paraDao.selectParaByParaId(tblCaseStep.getOperateWriteParaId());
							scriptHead.append("var "+writeTblPara.getParaName()+"=null;\r\n");
						}
						scriptBody.append(getControlCode(tblCaseStep,readTblPara,writeTblPara,deviceInfo.getScreenHeight(),1,deviceInfo.getPlatform()));
					}
					String filepath = targetFilePath+"script/"+tblTestTaskCase.getCaseId();
					OutputStream oStream = null;
					String targetFile =filepath+"/"+tblTestTaskCaseDevice.getDeviceId()+".js";
					try {
						File filePathFile = new File(filepath);
						if (!filePathFile.exists()) {
							filePathFile.mkdirs();
						}
						StringBuilder result = new StringBuilder();
						File modelFile = new File(targetFilePath+"script/scriptModel.test.js");
						BufferedReader br = new BufferedReader(new FileReader(modelFile));//构造一个BufferedReader类来读取文件
			            String s = null;
			            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
			                result.append(System.lineSeparator()+s);
			            }
			            br.close();
						File file = new File(targetFile); 
						if("ios".equals(deviceInfo.getPlatform())) {
							scriptData = result.toString().replaceAll("#scriptHead#", scriptHead.toString())
									.replace("#devicesName#",deviceInfo.getModel())
									.replace("#device-ios-udid#",deviceInfo.getSerialNumber())
									.replace("#script-reuse#", "2");
						}else {
							scriptData = result.toString().replaceAll("#scriptHead#", scriptHead.toString())
									.replace("#device-android-targetPixel#", deviceInfo.getScreenWidth()+"x"+deviceInfo.getScreenHeight())
									.replace("#script-reuse#", "2");
						}
						scriptData+= scriptBody.toString()+"});";
						oStream = new FileOutputStream(file);
						oStream.write(scriptData.getBytes());
					} catch (Exception e) {
						try {
							if (oStream!=null) {
								oStream.close();
							}
						} catch (IOException e1) {
							e1.printStackTrace();
						}
						e.printStackTrace();
					}
					TblAttachment attachment = new TblAttachment();
					attachment.setCreateTime(new Timestamp(new Date().getTime()));
					attachment.setFilePath(targetFile);
					attachment.setCreateUserId(1L);
					attachment.setFileNameNew(tblTestTaskCaseDevice.getDeviceId().toString());
					attachment.setFileNameOld(tblTestTaskCaseDevice.getDeviceId().toString());
					attachment.setFileType("js");
					attachmentDao.saveFile(attachment);
					
					TblTestTaskCaseRunWithBLOBs taskCaseRun = new TblTestTaskCaseRunWithBLOBs();
					taskCaseRun.setCaseId(tblTestTaskCase.getCaseId());
					taskCaseRun.setDeviceId(tblTestTaskCaseDevice.getDeviceId());
					taskCaseRun.setTestTaskId(taskId);
					taskCaseRun.setScriptContent(scriptData);
					taskCaseRun.setScriptId(attachment.getId().intValue());
					taskCaseRun.setTestTaskRunStatus((long)Constants.TASK_EXCECUTION_WAIT);
					tblTestTaskCaseRunMapper.insertTaskCaseRun(taskCaseRun);
				}
			}
		
	}
	
	@Override
	public Long generateScriptByCaseId(Long caseId,Integer deviceId,int reuse) {
		List<TblCaseStep> caseSteps = caseStepDao.selectStepByCaseId(caseId);
		TblDeviceInfo deviceInfo = deviceInfoDao.selectByPrimaryKey(deviceId);
		StringBuffer scriptHead = new StringBuffer();
		StringBuffer scriptBody = new StringBuffer();
		for (TblCaseStep tblCaseStep : caseSteps) {
			TblPara readTblPara = null;
			TblPara writeTblPara = null;
			if (tblCaseStep.getOperateReadParaId()!=null) {
				readTblPara = paraDao.selectParaByParaId(tblCaseStep.getOperateReadParaId());
				scriptHead.append("var "+readTblPara.getParaName()+"=null;\r\n");
			}
			if (tblCaseStep.getOperateWriteParaId()!=null) {
				writeTblPara = paraDao.selectParaByParaId(tblCaseStep.getOperateWriteParaId());
				scriptHead.append("var "+writeTblPara.getParaName()+"=null;\r\n");
			}
			scriptBody.append(getControlCode(tblCaseStep,readTblPara,writeTblPara,deviceInfo.getScreenHeight(),2,deviceInfo.getPlatform()));
		}
		String filepath = targetFilePath+"script/"+caseId;
		OutputStream oStream = null;
		try {
			File filePathFile = new File(filepath);
			if (!filePathFile.exists()) {
				filePathFile.mkdirs();
			}
			File modelFile = new File(targetFilePath+"script/scriptModel.test.js");
			StringBuilder result = new StringBuilder();
			BufferedReader br = new BufferedReader(new FileReader(modelFile));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result.append(System.lineSeparator()+s);
            }
            br.close();
			File file = new File(filepath+"/"+deviceId+".js"); 
			String scriptData = result.toString().replaceAll("#scriptHead#", scriptHead.toString())
					.replace("#device-android-targetPixel#", deviceInfo.getScreenWidth()+"x"+deviceInfo.getScreenHeight())
					.replace("#script-reuse#", reuse+"");
			scriptData+= scriptBody.toString()+"});";
			oStream = new FileOutputStream(file);
			oStream.write(scriptData.getBytes());
			TblAttachment attachment = new TblAttachment();
			attachment.setCreateTime(new Timestamp(new Date().getTime()));
			attachment.setFilePath(targetFilePath+"script/"+caseId+"/"+deviceId+".js");
			attachment.setCreateUserId(SecurityUserHolder.getCurrentUser().getId());
			attachment.setFileNameNew(deviceId.toString());
			attachment.setFileNameOld(deviceId.toString());
			attachment.setFileType("js");
			attachmentDao.saveFile(attachment);
			return attachment.getId();
		} catch (Exception e) {
			
			try {
				if (oStream!=null) {
					oStream.close();
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 生成步骤脚本
	 * @param TblCaseStep 步骤
	 * @param TblPara 参数类型
	 * @param Integer 设备像素高度
	 * @param Integer 脚本类型（1：自动化脚本 2：页面预览）
	 * 
	 * @return String 步骤脚本
	 * */
	private String getControlCode(TblCaseStep tblCaseStep,TblPara readTblPara,TblPara writeTblPara,Integer height,Integer scriptType,String platForm) {
		float bill =1;
		if(!"ios".equals(platForm)) {
			bill = ((float)(height)/(float)500);
		}
		String controlCode ="";
		controlCode+="	it('步骤"+tblCaseStep.getStepOrder()+"', function() {\r\n";
		controlCode+="		return driver\r\n";
		controlCode += "		.sleep(1000)\r\n";
		TblControls controls = controlDao.selectControlById(tblCaseStep.getOperateControlId());
		//1:点击，2:长按，3:输入，4:读取，5:滚动区域搜索，6:内容匹配点击，7:图片匹配点击
		if (tblCaseStep.getOperateType()==1) {
			if (controls.getControlLocationType()==1) {//1:点击
				controlCode += "		.elementByXPath('"+controls.getControlCode()+"')\r\n";
				controlCode += "		.click()\r\n";
			}else if (controls.getControlLocationType()==2) {
				String[] xys = controls.getControlXY().split(",");
				controlCode += "		.touch('tap', { x: "+(int)(Float.valueOf(xys[0])*bill)+", y: "+(int)(Float.valueOf(xys[1])*bill)+"})\r\n";
			}
		}else if (tblCaseStep.getOperateType()==2) {//2:长按
			if (controls.getControlLocationType()==1) {
				controlCode += "		.elementByXPath('"+controls.getControlCode()+"')\r\n";
				controlCode += "		.touch('press', { duration: 2 })\r\n";
			}else if (controls.getControlLocationType()==2) {
				String[] xys = controls.getControlXY().split(",");
				controlCode += "		.touch('press', { x: "+(int)(Float.valueOf(xys[0])*bill)+", y: "+(int)(Float.valueOf(xys[1])*bill)+"})\r\n";
			}
		}else if (tblCaseStep.getOperateType()==3) {//3:输入
			
			Integer readRule = tblCaseStep.getOperateReadRule();
			TblParaData tblParaData = this.selectParaDataNoUsedByParaIdAndRule(readTblPara,readRule,scriptType);
			//TblParaData tblParaData = paraDataDao.selectParaDataNoUsedByParaId(tblPara.getId());
			if (controls.getControlLocationType()==1) {
				controlCode += "		.elementByXPath('"+controls.getControlCode()+"')\r\n";
			}else if (controls.getControlLocationType()==2) {
				String[] xys = controls.getControlXY().split(",");
				controlCode += "		.touch('tap', { x: "+(int)(Float.valueOf(xys[0])*bill)+", y: "+(int)(Float.valueOf(xys[1])*bill)+"})\r\n";
			}
			if (tblParaData!=null) {
				controlCode += "		.sendKeys('"+tblParaData.getParaData()+"')\r\n";
			}else {
				controlCode += "		.sendKeys('')\r\n";
			}
		}else if (tblCaseStep.getOperateType()==4) {//4:读取
			if (controls.getControlLocationType()==1) {
				controlCode += "		.elementByXPath('"+controls.getControlCode()+"')\r\n";
				controlCode += "		.text()\r\n";
				controlCode += "		.sleep(1000)\r\n";
			}else if (controls.getControlLocationType()==2) {
				String[] xys = controls.getControlXY().split(",");
				controlCode += "		.touch('tap', { x: "+(int)(Float.valueOf(xys[0])*bill)+", y: "+(int)(Float.valueOf(xys[1])*bill)+"})\r\n";
				controlCode += "		.text()\r\n";
				controlCode += "		.sleep(1000)\r\n";
			}
			if (writeTblPara!=null) {
				controlCode += "		.then(text => {\r\n";
				controlCode += "		"+writeTblPara.getParaName()+"=text;\r\n";
				controlCode += "	})\r\n";
			}
		}else if (tblCaseStep.getOperateType()==5) {//5:滚动区域搜索scrollToElementByName
			Integer readRule = tblCaseStep.getOperateReadRule();
			TblParaData tblParaData = this.selectParaDataNoUsedByParaIdAndRule(readTblPara,readRule,scriptType);
			controlCode += "		.scrollToElementByName('"+tblParaData.getParaData()+"')\r\n";
			controlCode += "		.click()\r\n";
			controlCode += "		.sleep(1000)\r\n";
		}else if (tblCaseStep.getOperateType()==6) {//6:内容匹配点击
			Integer readRule = tblCaseStep.getOperateReadRule();
			TblParaData tblParaData = this.selectParaDataNoUsedByParaIdAndRule(readTblPara,readRule,scriptType);
			Integer startX =(int)(Float.valueOf(controls.getControlStartXY().split(",")[0])*bill);
			Integer startY =(int)(Float.valueOf(controls.getControlStartXY().split(",")[1])*bill);
			Integer endX =  (int)(Float.valueOf(controls.getControlWidth())*bill)+startX;
			Integer endY =  (int)(Float.valueOf(controls.getControlHeight())*bill)+startY;
			controlCode += "		.source()\r\n";
			controlCode += "		.then(sourceStr => {\r\n";
			controlCode += "		     var formData = {\r\n";
			controlCode += "		            source:sourceStr,\r\n";
			controlCode += "		            startX:"+startX+",\r\n";
			controlCode += "		            startY:"+startY+",\r\n"; 
			controlCode += "		            endX:"+endX+",\r\n";
			controlCode += "		            endY:"+endY+",\r\n";
			controlCode += "		            seachString:'"+tblParaData.getParaData()+"'};\r\n";
			controlCode += "			 request.post({\r\n";
			controlCode += "			     url: 'http://"+serverIP+":"+serverPort+"/wsServices/getQuestionResolution',\r\n";
			controlCode += "			    formData: formData\r\n";
			controlCode += "			}, function(err, httpResponse, body) {\r\n";
			controlCode += "			  if (err) {\r\n";
			controlCode += "			   console.log('upload failed:', err);\r\n";
			controlCode += "			 }\r\n";
			controlCode += "			 console.log('Server responded with:', body);\r\n";
			controlCode += "			 touchX=parseInt(body.split(',')[0]);\r\n";
			controlCode += "			 touchY=parseInt(body.split(',')[1]);\r\n";
			controlCode += "			driver.touch('tap', { x: parseInt(touchX), y: parseInt(touchY)})\r\n";
			controlCode += "			})\r\n";
			controlCode += "		})\r\n";
			controlCode += "		.sleep(5000)\r\n";
		}else if (tblCaseStep.getOperateType()==7) {//7:图片匹配点击
			TblAttachment attachment = attachmentDao.selectFileById(controls.getControlImageAttachmentId());
			TblControls parantComtrol = controlDao.selectControlById(controls.getParentId());
			int startX =(int)(Float.valueOf(parantComtrol.getControlStartXY().split(",")[0])*bill);
			int startY =(int)(Float.valueOf(parantComtrol.getControlStartXY().split(",")[1])*bill);
			String tagetFile = targetFilePath+"temp/"+UUID.randomUUID()+".png";
			PictureTool.convert(targetFilePath+attachment.getFilePath(), "png", tagetFile);
			String afterBase64 = null;
			File file = new File(tagetFile);
			try {
				BufferedImage imageFirst = ImageIO.read(file);
				float bill2 = ((float)(height)/(float)controls.getScreenHeight());
				BufferedImage image = PictureTool.resize(imageFirst,(int)(imageFirst.getWidth()*bill2) , (int)(imageFirst.getHeight()*bill2));
				String taget2File = targetFilePath+"temp/"+UUID.randomUUID()+".png";
				 File outFile = new File(taget2File);
				ImageIO.write(image, "png", outFile);// 写图片
				afterBase64=PictureTool.GetImageStr(taget2File);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			//String afterBase64 = (attachment==null || attachment.getFilePath()==null)?"":PictureTool.GetImageStr(tagetFile);
			controlCode += "		.takeScreenshot()\r\n";
			controlCode += "		.then(base64Data=> {\r\n";
			controlCode += "			var image1 = path.join(__dirname, '..', 'source"+tblCaseStep.getStepOrder()+".png');\r\n";
			controlCode += "			var dataBuffer = new Buffer(base64Data, 'base64');\r\n";
			controlCode += "			fs.writeFileSync(image1, dataBuffer);\r\n";
			controlCode += "			var image2 = path.join(__dirname, '..', 'crop"+tblCaseStep.getStepOrder()+".png');\r\n";
			controlCode += "		     var formData1 = {\r\n";
			controlCode += "		            attachments: [\r\n";
			controlCode += "		            fs.createReadStream(image1)\r\n";
			controlCode += "		     ],};\r\n";

			controlCode += "		     var udid = UUID.v1();\r\n";
			controlCode += "		     request.post({\r\n";
			controlCode += "		               url: 'http://"+serverIP+":"+serverPort+"/wsServices/crop/"+startX+"/"+startY+"/"+
													(int)(Float.valueOf(parantComtrol.getControlWidth())*bill)+"/"+
													(int)(Float.valueOf(parantComtrol.getControlHeight())*bill)+"/'+udid,\r\n";
			controlCode += "		               formData: formData1\r\n";
			controlCode += "		           }, function optionalCallback(err, httpResponse, body) {\r\n";
			controlCode += "		               var dataBuffer = new Buffer(body, 'base64');\r\n";
			controlCode += "		                fs.writeFileSync(image2, dataBuffer);\r\n";
			controlCode += "		            });\r\n";
			controlCode += "			driver.sleep(1000);\r\n";
			controlCode += "			var image3 = path.join(__dirname, '..', 'touch"+tblCaseStep.getStepOrder()+".png');\r\n";
			controlCode += "			var base64Data2='"+afterBase64+"';\r\n";
			controlCode += "			var dataBuffer2 = new Buffer(base64Data2, 'base64');\r\n";
			controlCode += "			fs.writeFileSync(image3, dataBuffer2);\r\n";
			controlCode += "		})\r\n";
			controlCode += "		.sleep(1000)\r\n";
			controlCode += "		.then(()=> {\r\n";
			controlCode += "			var image1 = path.join(__dirname, '..', 'crop"+tblCaseStep.getStepOrder()+".png');\r\n";
			controlCode += "			var image2 = path.join(__dirname, '..', 'touch"+tblCaseStep.getStepOrder()+".png');\r\n";
			controlCode += "			var formData = {\r\n";
			controlCode += "			        image1: [\r\n";
			controlCode += "			        fs.createReadStream(image1)\r\n";
			controlCode += "			 ],image2: [\r\n";
			controlCode += "			  fs.createReadStream(image2)\r\n";
			controlCode += "			],\r\n";
			controlCode += "			 };\r\n";
			controlCode += "			 request.post({\r\n";
			controlCode += "			     url: '"+openCvServer+"/opencv/matchtemplate',\r\n";
			controlCode += "			    formData: formData\r\n";
			controlCode += "			}, function(err, httpResponse, body) {\r\n";
			controlCode += "			  if (err) {\r\n";
			controlCode += "			   console.log('upload failed:', err);\r\n";
			controlCode += "			 }\r\n";
			controlCode += "			 console.log('Server responded with:', body);\r\n";
			//controlCode += "			 try {\r\n";
			controlCode += "			 const data = JSON.parse(body);\r\n";
			controlCode += "			 touchX=parseInt("+startX+"+parseInt(data.match[1])+(parseInt(data.match[3])/2));\r\n";
			controlCode += "			 touchY=parseInt("+startY+"+parseInt(data.match[2])+(parseInt(data.match[4])/2));\r\n";
			/*controlCode += "			 touchX=data.match[1];\r\n";
			controlCode += "			 touchY=data.match[2];\r\n";*/

			controlCode += "			driver.touch('tap', { x: parseInt(touchX), y: parseInt(touchY)})\r\n";
			controlCode += "			 console.log(`matchtemplate is: ${data.match}`);\r\n";
			/*controlCode += "			} catch (e) {\r\n";
			controlCode += "			   console.log(`matchtemplate is: ${e}`);\r\n";
			controlCode += "			}\r\n";*/
			controlCode += "			 });\r\n";
			controlCode += "		})\r\n";
			controlCode += "		.sleep(10000)\r\n";
			//controlCode += "		.touch('tap', { x: parseInt(touchX), y: parseInt(touchY)})\r\n";
			//controlCode += "		.sleep(1000)\r\n";
			
		}
		controlCode+="		.sleep("+(tblCaseStep.getWaitingSecs()*1000)+")\r\n";
		//断言    1:无，2:文本内容包括，3：发现控件，4:变量运算
		if (tblCaseStep.getExpectType()==2) {
			TblPara containTblPara = paraDao.selectParaByParaId(tblCaseStep.getExpectReadParaId());
			controlCode += "		.sleep(1000)\r\n";
			controlCode += "		.source()\r\n";
			controlCode += "		.then(sourceStr => {\r\n";
			controlCode += "			sourceStr.should.containEql('"+this.selectParaDataNoUsedByParaIdAndRule(containTblPara,1,scriptType).getParaData()+"');\r\n";
			controlCode += "		})\r\n";
		}else if (tblCaseStep.getExpectType()==3) {
			TblControls findControls = controlDao.selectControlById(tblCaseStep.getExpectControlId());
			controlCode += "		.sleep(1000)\r\n";
			controlCode += "		.hasElementByXPath('"+findControls.getControlCode()+"')\r\n";
			controlCode += "		.then(hasFlage => {\r\n";
			controlCode += "			hasFlage.should.be.true();\r\n";
			controlCode += "		})\r\n";
		}else if (tblCaseStep.getExpectType()==4) {
			controlCode += "		.sleep(1000)\r\n";
			controlCode += "		.then(()=> {\r\n";
			controlCode += "			("+tblCaseStep.getExpectParaOperation()+").should.be.true();\r\n";
			controlCode += "		})\r\n";
		}
		
		
		
		controlCode+="		.saveScreenshot('步骤"+tblCaseStep.getStepOrder()+".png');\r\n";
		controlCode+="	});\r\n";
		return controlCode;
	}

	private TblParaData selectParaDataNoUsedByParaIdAndRule(TblPara tblPara, Integer readRule,Integer scriptType) {
		List<TblParaData> tblParaDatas = null;
		TblParaData tblParaData=null;
		//1:顺序，2:随机，3:唯一
		if (readRule.equals(1)) {
			tblParaDatas = paraDataDao.selectOrderParaDataByParaId(tblPara.getId());
			tblParaData = tblParaDatas.get(0);
		}else if (readRule.equals(2)) {
			tblParaDatas = paraDataDao.selectRandomParaDataByParaId(tblPara.getId());
			Random random = new Random();
		    int s = random.nextInt(tblParaDatas.size());
		    tblParaData = tblParaDatas.get(s);
		}else {
			tblParaDatas = paraDataDao.selectParaDataNoUsedByParaId(tblPara.getId());
			tblParaData = tblParaDatas.get(0);
		}
		if (2!=scriptType) {
			paraDataDao.updateParaDatasetUsed(tblParaData.getId());
		}
		return tblParaData;
	}
	@Override
	public Map<String,Object> recording(Long caseId,Long deviceId,int reuse) {
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		if (caseId != null) {
			TblCaseInfo caseInfo = caseInfoDao.selectCaseById(caseId);
			TblAppInfo projectApp = iAppInfoService.selectAppById(caseInfo.getAppId());
			// 设置设备类型
			TblDeviceInfo deviceInfo = new TblDeviceInfo();
			deviceInfo = deviceService.geTblDeviceInfoById(deviceId);
			// 向batchSubTask保存设备类型
			String deviceTypeVo = deviceInfo.getPlatform();

			// iTaskCaseRunService.insertTaskCaseRun(batchSubTask);

			if (projectApp != null) {
				Integer platform = projectApp.getPlatform();
				String platForm = "";
				if (DeviceConstants.AUTO_APP_PLATFORM_ANDROID == platform.intValue()) {
					platForm = "android";
				} else {
					platForm = "ios";
				}

				// 检查设备的平台跟案例上选择的应用的平台是否相同，相同的才创建job
				if (!deviceInfo.getPlatform().toUpperCase().contains(platForm.toUpperCase().toString())) {
					result.put("status", Constants.RETURN_FAIL);
					result.put("errorMsg", "所选设备与案例的应用的平台不一致，请重新选择");
					return result;
				}


				JobParameter jobParameter = new JobParameter();

				// 设置应用类型
				jobParameter.setAppType(projectApp.getAppType());

				jobParameter.setDeviceType(deviceInfo.getDeviceType());
				jobParameter.setDeviceId(deviceInfo.getUdid());
				jobParameter.setPlay("1");
				jobParameter.setAppUrl(DeviceUtil.getDemoServerAppUrl(serverIP, serverPort, Long.valueOf(caseInfo.getAppId())));

				jobParameter.setResultUrl(DeviceUtil.getDemoServerResultUrl(serverIP, serverPort, Long.valueOf(caseId),null));
				Long scriptId =	this.generateScriptByCaseId(caseId, deviceId.intValue(),reuse);
				jobParameter.setScriptUrl(DeviceUtil.getDemoServerScriptUrl(serverIP, serverPort, scriptId));

				jobParameter.setJobStatusUrl(DeviceUtil.getDemoJobStatusUrl(serverIP, serverPort));

				WSClient wsClient = new WSClient(DeviceUtil.getMatcServer(relibleMasterIp, 3333));
				try {
					String jobIdString = wsClient.submitJob(jobParameter);
				} catch (Exception e) {
					e.printStackTrace();
					log.error("脚本预览失败"+e.getMessage());
					result.put("status", Constants.RETURN_FAIL);
					result.put("errorMsg", "脚本预览失败");
					return result;
				}
			}

		}
		return result;
	}
}
